<template>
  <div class="video-player-container">
    <div ref="videoContainer" class="video-wrapper"></div>
    <div v-if="loading" class="loading-overlay">
      <el-icon class="loading-icon"><Loading /></el-icon>
      <span class="loading-text">加载中...</span>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'

// 直接导入npm安装的video.js
import videojs from 'video.js'
import 'video.js/dist/video-js.css'

// 尝试导入并注册hls插件，但不作为必要依赖
let registerHlsJsPlugin = null
try {
  import('videojs-hlsjs-plugin').then(module => {
    registerHlsJsPlugin = module.default || module
  })
} catch (error) {
  console.warn('[Player Debug] videojs-hlsjs-plugin not found or could not be loaded:', error)
}

// 定义组件属性
const props = defineProps({
  src: {
    type: String,
    required: true,
    default: ''
  },
  autoplay: {
    type: Boolean,
    default: false
  },
  controls: {
    type: Boolean,
    default: true
  },
  muted: {
    type: Boolean,
    default: false
  },
  loop: {
    type: Boolean,
    default: false
  },
  startTime: {
    type: Number,
    default: 0
  }
})

// 定义组件事件
const emit = defineEmits(['play', 'pause', 'ended', 'error', 'ready', 'timeupdate'])

// 引用
const videoContainer = ref(null)
const loading = ref(true)
let player = null

// 初始化video.js和注册插件
const loadVideoJs = async () => {
  try {
    console.log('[Player Debug] Loading Video.js');
    
    // 确保全局可用
    if (!window.videojs) {
      window.videojs = videojs;
    }
    
    // 尝试注册HLS插件
    if (registerHlsJsPlugin && typeof registerHlsJsPlugin.register === 'function') {
      try {
        registerHlsJsPlugin.register(videojs)
        console.log('[Player Debug] HLS plugin registered successfully');
      } catch (pluginError) {
        console.warn('[Player Debug] Failed to register HLS plugin:', pluginError);
      }
    }
    
    return videojs;
  } catch (error) {
    console.error('[Player Debug] Error with video.js:', error);
    throw error;
  }
}

// 初始化播放器
const initPlayer = async () => {
  if (!videoContainer.value) {
    console.error('Video container is not available');
    return
  }
  
  if (!props.src) {
    console.error('No video source provided');
    loading.value = false;
    return
  }
  
  try {
    console.log('[Player Debug] Initializing player with source:', props.src);
    console.log('[Player Debug] Current props:', { autoplay: props.autoplay, muted: props.muted, controls: props.controls });
    
    // 检查URL格式
    try {
      new URL(props.src);
      console.log('[Player Debug] Valid URL format');
    } catch (e) {
      console.error('[Player Debug] Invalid URL format:', e);
    }
    
    // 等待DOM更新
    await nextTick()
    console.log('[Player Debug] DOM updated');
    
    // 确保video.js已加载
    const loadedVideoJs = await loadVideoJs();
    console.log('[Player Debug] Video.js loaded successfully');
    
    // 清除现有的播放器
    if (player) {
      player.dispose()
    }
    
    // 创建视频元素
    const videoId = `video-player-${Date.now()}`
    console.log('[Player Debug] Creating video element with ID:', videoId);
    
    // 打印将要创建的HTML内容用于调试
    const videoHtml = `
      <video
        id="${videoId}"
        class="video-js vjs-default-skin vjs-big-play-centered"
        controls
        preload="auto"
        ${props.autoplay ? 'autoplay' : ''}
        ${props.muted ? 'muted' : ''}
        ${props.loop ? 'loop' : ''}
        data-setup="{}"
      >
        <source src="${props.src}" type="application/x-mpegURL">
        您的浏览器不支持HTML5视频播放
      </video>
    `;
    
    // console.log('[Player Debug] Video element HTML:', videoHtml.trim());
    videoContainer.value.innerHTML = videoHtml;
    
    // 初始化播放器
    // 注意：现代浏览器要求自动播放时需要同时静音
    const autoPlayWithMuted = props.autoplay && !props.muted
    
    // 简化播放器配置，移除不存在的hlsjs插件配置
    const playerOptions = {
      controls: props.controls,
      autoplay: props.autoplay,
      muted: props.muted || autoPlayWithMuted, // 如果设置了自动播放但未静音，则强制静音
      loop: props.loop,
      preload: 'auto',
      techOrder: ['html5']
    };
    
    console.log('[Player Debug] Initializing video.js with options:', playerOptions);
    player = loadedVideoJs(videoId, playerOptions);
    console.log('[Player Debug] Player initialized successfully');
    
    // 监听视频源加载开始事件
    player.on('loadstart', () => {
      console.log('[Player Debug] Video source loading started');
      // 手动触发一次XHR请求检查
      const videoElement = document.getElementById(videoId);
      if (videoElement) {
        console.log('[Player Debug] Video element properties:', {
          src: videoElement.src,
          currentSrc: videoElement.currentSrc,
          readyState: videoElement.readyState,
          networkState: videoElement.networkState
        });
      }
    });
    
    // 监听canplaythrough事件，表示视频可以流畅播放
    player.on('canplaythrough', () => {
      console.log('[Player Debug] Video can play through without buffering');
    });
    
    // 监听waiting事件，表示正在缓冲
    player.on('waiting', () => {
      console.log('[Player Debug] Video is buffering');
    });
    
    // 监听stalled事件，表示网络连接中断
    player.on('stalled', () => {
      console.log('[Player Debug] Network connection stalled');
    });
    
    // 添加事件监听器
    player.on('play', () => {
      console.log('Video started playing:', props.src)
      emit('play')
    })
    player.on('pause', () => emit('pause'))
    player.on('ended', () => emit('ended'))
    player.on('error', (err) => {
      console.error('[Player Debug] Video error:', err, 'Source:', props.src);
      
      // 检查视频元素的错误状态
      const videoElement = document.getElementById(videoId);
      if (videoElement) {
        console.error('[Player Debug] Video element error state:', {
          error: videoElement.error,
          errorCode: videoElement.error ? videoElement.error.code : 'none',
          networkState: videoElement.networkState,
          readyState: videoElement.readyState
        });
      }
      
      // 提供更具体的错误信息
      let errorMessage = '视频播放出错';
      if (err && err.code) {
        console.error('[Player Debug] Error code:', err.code);
        switch(err.code) {
          case 4: // MEDIA_ERR_SRC_NOT_SUPPORTED
            errorMessage = '视频格式不支持或URL无效';
            break;
          case 3: // MEDIA_ERR_DECODE
            errorMessage = '视频解码失败';
            break;
          case 2: // MEDIA_ERR_NETWORK
            errorMessage = '网络错误，请检查网络连接';
            break;
          case 1: // MEDIA_ERR_ABORTED
            errorMessage = '视频加载被中止';
            break;
        }
      }
      emit('error', err);
      ElMessage.error(errorMessage);
    })
    
    // 监听加载进度事件
    player.on('progress', () => {
      const buffered = player.buffered()
      if (buffered.length > 0) {
        const bufferedEnd = buffered.end(buffered.length - 1)
        const duration = player.duration()
        if (duration > 0) {
          const bufferedPercent = (bufferedEnd / duration) * 100
          console.log(`Video buffered: ${bufferedPercent.toFixed(2)}%`)
        }
      }
    })
    
    // 监听加载完成
    player.one('loadeddata', () => {
      loading.value = false
      emit('ready')
    })

    // 添加timeupdate事件监听
    player.on('timeupdate', () => {
      const currentTime = player.currentTime()
      emit('timeupdate', currentTime)
    })
    
    // 监听loadedmetadata事件，设置起始播放时间
    player.on('loadedmetadata', () => {
      console.log('[Player Debug] Metadata loaded, attempting to seek to start time:', props.startTime);
      if (props.startTime > 0 && props.startTime < player.duration()) {
        player.currentTime(props.startTime);
        console.log('[Player Debug] Seek to start time successful');
      }
    })

    // 监听视频加载超时
    setTimeout(() => {
      if (loading.value) {
        loading.value = false
        ElMessage.warning('视频加载超时，请检查网络或URL是否正确')
      }
    }, 10000)
    
  } catch (error) {
    console.error('Failed to initialize video player:', error)
    loading.value = false
    ElMessage.error('播放器初始化失败')
  }
}

// 组件挂载后再初始化播放器
onMounted(() => {
  console.log('[Player Debug] Component mounted');
  // 组件挂载后，如果有src，则初始化播放器
  if (props.src) {
    loading.value = true
    initPlayer()
  }
})

// 监听src变化
watch(() => props.src, (newSrc) => {
  if (newSrc) {
    loading.value = true
    // 使用nextTick确保DOM更新后再初始化
    nextTick(() => {
      initPlayer()
    })
  }
})

// 监听控制属性变化
watch(() => props.controls, (newValue) => {
  if (player) {
    player.controls(newValue)
  }
})

watch(() => props.muted, (newValue) => {
  if (player) {
    player.muted(newValue)
  }
})

watch(() => props.loop, (newValue) => {
  if (player) {
    player.loop(newValue)
  }
})

// 提供播放控制方法
defineExpose({
  play: () => {
    console.log('[Player Debug] Play method called');
    return player?.play()
  },
  pause: () => {
    console.log('[Player Debug] Pause method called');
    return player?.pause()
  },
  togglePlay: () => {
    console.log('[Player Debug] Toggle play method called');
    if (player) {
      if (player.paused()) {
        console.log('[Player Debug] Current state: paused, attempting to play');
        player.play()
      } else {
        console.log('[Player Debug] Current state: playing, attempting to pause');
        player.pause()
      }
    }
  },
  seek: (time) => {
    console.log('[Player Debug] Seek method called with time:', time);
    return player?.currentTime(time)
  },
  getCurrentTime: () => {
    const time = player?.currentTime() || 0;
    console.log('[Player Debug] Get current time:', time);
    return time;
  },
  getDuration: () => {
    const duration = player?.duration() || 0;
    console.log('[Player Debug] Get duration:', duration);
    return duration;
  },
  // 获取视频截图功能
  getScreenshot: async (time) => {
    console.log('[Player Debug] Get screenshot called for time:', time);
    if (!player) {
      console.error('[Player Debug] No player instance available');
      return null;
    }
    
    try {
      // 如果指定了时间，先seek到该时间点
      const originalTime = player.currentTime();
      let screenshotTime = time || originalTime;
      
      if (time !== undefined) {
        player.currentTime(time);
        // 等待视频帧加载完成
        await new Promise(resolve => {
          const handleSeeked = () => {
            player.off('seeked', handleSeeked);
            resolve();
          };
          player.one('seeked', handleSeeked);
          
          // 添加超时处理
          setTimeout(() => {
            player.off('seeked', handleSeeked);
            resolve();
          }, 1000);
        });
      }
      
      // 创建canvas并绘制当前视频帧
      const videoElement = player.el().querySelector('video');
      if (!videoElement) {
        console.error('[Player Debug] No video element found');
        // 恢复原始时间
        if (time !== undefined) player.currentTime(originalTime);
        return null;
      }
      
      const canvas = document.createElement('canvas');
      canvas.width = videoElement.videoWidth || 640;
      canvas.height = videoElement.videoHeight || 360;
      
      const ctx = canvas.getContext('2d');
      ctx.drawImage(videoElement, 0, 0, canvas.width, canvas.height);
      
      // 将canvas内容转换为base64图片
      const screenshotData = canvas.toDataURL('image/png');
      
      // 恢复原始时间
      if (time !== undefined) player.currentTime(originalTime);
      
      console.log('[Player Debug] Screenshot captured successfully');
      return screenshotData;
    } catch (error) {
      console.error('[Player Debug] Error capturing screenshot:', error);
      // 发生错误时也尝试恢复原始时间
      if (time !== undefined) player.currentTime(originalTime);
      return null;
    }
  }
})



// 组件销毁时清理
onUnmounted(() => {
  console.log('[Player Debug] Component unmounted, disposing player');
  if (player) {
    player.dispose()
    player = null
  }
})
</script>

<style scoped>
.video-player-container {
  position: relative;
  width: 100%;
  height: 100%;
  /* min-height: 300px; */
}

.video-wrapper {
  width: 100%;
  height: 100%;
  /* min-height: 300px; */
}

.video-wrapper :deep(.video-js) {
  width: 100%;
  height: 100%;
  /* min-height: 300px; */
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 10;
}

.loading-icon {
  font-size: 48px;
  color: #fff;
  margin-bottom: 12px;
  animation: spin 1s linear infinite;
}

.loading-text {
  color: #fff;
  font-size: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>